package online.hxstart.code.concurrent.chapter12;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Client {

  public static final int port = 8080;
  public static final String host = "localhost";

  public static void main(String[] args) throws IOException, InterruptedException {
    System.out.println("Client Start...");
    Socket socket;
    socket = new Socket(host, port);
    // 创建一个流套接字并将其连接到指定主机上的指定端口号
    try (BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintStream out = new PrintStream(socket.getOutputStream())) {
      while (true) {
        // 读取服务器端数据
        // 向服务器端发送数据
        System.out.print("请输入: \t");
        String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
        out.println(str);
        String ret = input.readLine();
        System.out.println("服务器端返回过来的是: " + ret);
        // 如接收到 "OK" 则断开连接
        if ("OK".equals(ret)) {
          System.out.println("客户端将关闭连接");
          Thread.sleep(500);
          input.close();
          break;
        }
      }
    } catch (Exception e) {
      System.out.println("客户端异常:" + e.getMessage());
      throw e;
    }
  }
}
